<?php

namespace app\home\controller;

use think\Request;
use app\common\controller\Home;
use app\common\library\util\Ems;
use app\common\library\util\QRcodeUtil;
use app\common\library\util\PosterUtil;
use app\common\library\util\Secure;
use app\common\model\Business\Business;
use app\common\model\Business\Collection;
use app\common\model\Business\Commission;
use app\common\model\Business\Record;
use app\common\model\Region;
use app\common\model\Subject\Comment;
use app\common\model\Subject\Order;
use app\common\model\Subject\Subject;
use app\common\model\Subject\Teacher\Follow;
use app\common\model\Subject\Teacher\Teacher;
use fast\Random;

class Center extends Home
{
    public function __construct(Request $request)
    {
        $this->noLogin = [];
        parent::__construct($request);
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return $this->view->fetch("index");
    }
    public function profile(Request $request)
    {
        if($request->isGet()){
            return $this->fetch();
        }

        $password = $request->post('password','','trim');
        $data = [
            'mobile' => $request->post('mobile','','trim'),
            'nickname' => $request->post('nickname','','trim'),
            'email' => $request->post('email','','trim'),
            'password' => $password?$password:'123456',
            'gender' => $request->post('gender','0','trim'),
        ];
        if(Business::where(['id'=>['<>',$this->business['id']],'mobile'=>$data['mobile']])->find())
        {
            $this->error('手机号已存在');
        }
        if(Business::where(['id'=>['<>',$this->business['id']],'email'=>$data['email']])->find())
        {
            $this->error('邮箱已存在');
        }
        // halt($data);
        if($data['email']==$this->business['email']){
            unset($data['email']);
        }else{
            $data['auth'] = 0;
        }
        $status = $this->upload();
        $preImgFile = '';
        if($status['code']==1){
            $preImgFile = ROOT_PATH . 'public' . $this->business['avatar'];
            $data['avatar'] = $status['msg'];
        }else if($status['code']==2){
            $this->error($status['msg'],'/home/center/profile');
        }
        
        if($data['mobile']==$this->business['mobile']){
            $result = $this->validate($data,"app\\common\\validate\\Business\\Business");
            unset($data['mobile']);
        }else{
            $result = $this->validate($data,"app\\common\\validate\\Business\\Business");
        }
        if(true !== $result){
            // 验证失败 输出错误信息
            $this->error($result,"/home/center/profile");
        }
        $code = $request->post('code','0','trim');
        $region = Region::where('code',$code)->find();
        if($region){
            $parentpath = explode(',',$region['parentpath'].',,');
            $data['province'] = $parentpath[0];
            $data['city'] = $parentpath[1];
            $data['district'] = $parentpath[2];
        }
        
        if(!$password){
            unset($data['password']);
        }else{
            $data['salt'] = Random::alnum(10);
            $data['password'] = md5(md5($password) . $data['salt']);
        }
        // halt(($data));
        $this->business->save($data,['id'=>$this->business['id']]);
        if($preImgFile&&is_file($preImgFile)){
            unlink($preImgFile);
        }
        $this->success('修改成功',"/home/center/profile");
    }
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('avatar');
        $status = ['code'=>0];
        if(!$file){
            $status['msg'] = '';
            return $status;
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . '/' . 'uploads');
        if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            // echo $info->getExtension();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
            // echo $info->getFilename(); 
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            $status['code'] = 1;
            $status['msg'] = '/' . 'uploads' . '/' . $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            $status['code'] = 1;
            $status['msg'] = $file->getError();
        }
        return $status;
    }
    public function email(Request $request)
    {
        if($this->business['auth']){
            return $this->success('邮箱已认证','/home/center/index');
        }
        if($request->isGet()){
            return $this->fetch();
        }
        $status = Ems::checkCode($this->business['email'],$request->post('code'));
        if($status['code']==1){
            $this->business['auth'] = 1;
            $this->business->save();
            return $this->success($status['msg'],'/home/center/index');
        }else{
            return $this->error($status['msg']);
        }
    }
    public function send()
    {
        return Ems::send($this->business['email']);
    }
    public function poster(Request $request)
    {
        $token = Secure::encrypt($this->business['mobile']);
        $link = url('/home/index/login',['token'=>$token],true,true);
        if($request->isGet())
        {
            if(!is_file(ROOT_PATH.'public'.$this->business['poster'])){
                $avatar_text = $this->business['avatar_text'];
                $qrcode_text = QRcodeUtil::createQRcode($link,$avatar_text);
                PosterUtil::createPoster($this->business['nickname'],$avatar_text,$qrcode_text);
            }
            $this->assign('link',$link);
            return $this->fetch();
        }
        // $avatarPath = $request->domain().$this->business['avatar_text'];
        $avatar_text = $this->business['avatar_text'];
        $qrcode_text = QRcodeUtil::createQRcode($link,$avatar_text);
        // halt($qrcode_text);
        $status = PosterUtil::createPoster($this->business['nickname'],$avatar_text,$qrcode_text);
        // halt($status);
        if($status['code']){
            $this->business['poster'] = $status['msg'];
            $this->business->save();
            $status['link'] = $link;
        }
        return $status;
    }
    public function team(Request $request)
    {
        if($request->isGet()){
            return $this->fetch();
        }
        // var pageNum = page.num; // 页码, 默认从1开始 如何修改从0开始 ?
        // var pageSize = page.size; // 页长, 默认每页10条
        $pageNum = $request->post('pageNum')?$request->post('pageNum'):1;
        $pageSize = $request->post('pageSize')?$request->post('pageSize'):3;
        $keyword = $request->post('keyword')?trim($request->post('keyword')):'';
        $team = Business::field('avatar,nickname,gender,createtime,province,city,district,poster')
                ->where(['parentid'=>$this->business['id'],'nickname'=>['like','%'.$keyword.'%']])
                ->limit(($pageNum-1)*$pageSize,$pageSize)
                ->select();
        // var curPageData = data.curPageData; // 接口返回的当前页数据列表
        //     var totalPage = data.totalPage; // 接口返回的总页数 (比如列表有26个数据,每页10条,共3页; 则totalPage值为3)
        //     var totalSize = data.totalSize; // 接口返回的总数据量(比如列表有26个数据,每页10条,共3页; 则totalSize值为26)
        //     var hasNext = data.hasNext;
        $page = [];
        $page['curPageData'] = $team;
        $page['totalPage'] = ceil(Business::where(['parentid'=>$this->business['id'],'nickname'=>['like','%'.$keyword.'%']])->count()/$pageSize);
        return $page;
    }
    public function collection(Request $request){
        if($request->isGet()){
            return $this->fetch();
        }
        if($request->isPost()){
            $subjectid = $request->post('id');
            if($subjectid){
                $subject = Subject::where('id',$subjectid)->find();
                // halt($subject);
                if(!$subject){
                    return $this->error('请求失敗','/home/subject');
                }
                $busid = $this->business['id'];
                $collection = Collection::where(['busid'=>$busid,'collectid'=>$subjectid,'status'=>'subject'])->find();
                $status = ['code'=>0];
                if($collection){
                    $result = $collection->delete();
                    if($result){
                        $status['code'] = 1;
                        $status['msg'] = '取消成功';
                        $status['isCollection'] = false;
                    }else{
                        $status['msg'] = '取消失败';
                    }
                }else{
                    $data = [
                        'busid'=>$busid,
                        'collectid'=>$subjectid,
                        'status'=>'subject'
                    ];
                    $result = Collection::create($data);
                    if($result){
                        $status['code'] = 1;
                        $status['msg'] = '收藏成功';
                        $status['isCollection'] = true;
                    }else{
                        $status['msg'] = '收藏失败';
                    }
                }
                return $status;    
            }else{
                $pageNum = $request->post('pageNum')?$request->post('pageNum'):1;
                $pageSize = $request->post('pageSize')?$request->post('pageSize'):5;
                $busid = $this->business['id'];
                $where = ['busid'=>$busid,'status'=>'subject'];
                $subject = Collection::where($where)
                        ->order('createtime','desc')
                        ->limit(($pageNum-1)*$pageSize,$pageSize)
                        ->select();
    
                $page = [];
                $page['curPageData'] = $subject;
                $page['totalPage'] = ceil(Collection::where($where)->count()/$pageSize);
                return $page;
            }
        }
    }
    public function follow(Request $request){
        if($request->isGet()){
            return $this->fetch();
        }
        if($request->isPost()){
            $pageNum = $request->post('pageNum')?$request->post('pageNum'):1;
            $pageSize = $request->post('pageSize')?$request->post('pageSize'):5;
            $keyword = $request->post('keyword')?$request->post('keyword'):'';
            $busid = $this->business['id'];
            $where = ['busid'=>$busid];
            $follows = Follow::where($where)
                    ->order('createtime','desc')
                    ->limit(($pageNum-1)*$pageSize,$pageSize)
                    ->select();
            $follows = $follows?$follows:collection([]);
            $follows->each(function($follow){
                $follow['teacher'] = Teacher::where('id',$follow['teacherid'])->find();
                // halt($follow['teacher']);
            });
            if($keyword){
                $follows = $follows->filter(function($follow) use ($keyword){
                    return true&&stristr($follow['teacher']['name'],$keyword);
                });
            }
            // halt($follow['teacher']);
            $page = [];
            $page['curPageData'] = $follows;
            $page['totalPage'] = ceil(follow::where($where)->count()/$pageSize);
            return $page;
        }
    }
    public function record(Request $request)
    {
        if($request->isGet()){
            return $this->fetch();
        }
        $pageNum = $request->post('pageNum')?$request->post('pageNum'):1;
        $pageSize = $request->post('pageSize')?$request->post('pageSize'):5;
        $keyword = $request->post('keyword')?trim($request->post('keyword')):'';
        $busid = $this->business['id'];
        $where = ['busid'=>$busid,'content'=>['like','%'.$keyword.'%']];
        $record = Record::where($where)
                ->order('createtime','desc')
                ->limit(($pageNum-1)*$pageSize,$pageSize)
                ->select();

        $page = [];
        $page['curPageData'] = $record;
        $page['totalPage'] = ceil(Record::where($where)->count()/$pageSize);
        return $page;
    }
    public function money(Request $request)
    {
        if($request->isGet())
        {
            return $this->fetch();
        }
        $pageNum = $request->post('pageNum')?$request->post('pageNum'):1;
        $pageSize = $request->post('pageSize')?$request->post('pageSize'):5;
        $option = $request->post('option')?trim($request->post('option')):0;
        $parentid = $this->business['id'];
        $where = ['parentid'=>$parentid,'type'=>'subject'];
        switch($option)
        {
            case 1:
                $where['status'] = 0;
                break;
            case 2:
                $where['status'] = 1;
                break;
        }
        $commission = Commission::where($where)
                ->order('createtime','desc')
                ->limit(($pageNum-1)*$pageSize,$pageSize)
                ->select();

        $page = [];
        $page['curPageData'] = $commission;
        $page['totalPage'] = ceil(Commission::where($where)->count()/$pageSize);
        return $page;
    }
    public function withdraw(Request $request)
    {
        $id = $request->get('id');
        $commission = Commission::where('id',$id)->find();
        if(!$commission){
            $this->error('找不到可提现佣金','/home/center/money');
        }
        $status = [];
        Commission::startTrans();
        Business::startTrans();
        try{
            $commission['status'] = 1;
            $commission->save();
            $this->business['money'] += $commission['amount'];
            Commission::commit();
            Business::commit();
            $status = ['code'=>1,'msg'=>'提现成功'];
        }catch(\Exception $e){
            $status = ['code'=>0,'msg'=>'提现失败'];
            Commission::rollback();
            Business::rollback();
        }
        return $status;
    }
    public function contact()
    {
        return $this->fetch();
    }
    public function order(Request $request)
    {
        if($request->isGet())
        {
            return $this->fetch();
        }
        $pageNum = $request->post('pageNum')?$request->post('pageNum'):1;
        $pageSize = $request->post('pageSize')?$request->post('pageSize'):5;
        $option = $request->post('option')?trim($request->post('option')):0;
        $busid = $this->business['id'];
        $where = ['busid'=>$busid];
        $orders = Order::where($where)
                ->order('createtime','desc')
                ->limit(($pageNum-1)*$pageSize,$pageSize)
                ->select();
        $orders = $orders->filter(function($order)use($option){
                switch($option)
            {
                case 0:
                    return true;
                case 1:
                    return !$order['iscomment'];
                case 2:
                    return $order['iscomment'];
            }
        });
        $total = Order::where($where)->select()->filter(function($order)use($option){
                switch($option)
            {
                case 0:
                    return true;
                case 1:
                    return !$order['iscomment'];
                case 2:
                    return $order['iscomment'];
            }
        })->count();
        $page = [];
        $page['curPageData'] = $orders;
        $page['totalPage'] = ceil($total/$pageSize);
        return $page;
    }
    public function comment(Request $request)
    {
        $orderid = $request->param('id');
        $order = Order::where('id',$orderid)->find();
        // halt($order);
        if(!$order||$order['busid']!=$this->business['id']){
            $this->error('订单不存在或无权访问','/home/center/order');
        }
        $comment = $order->hasOne('app\common\model\Subject\Comment','orderid','id')->find();
        if($request->isGet()){
            // halt($order['iscomment']);
            $this->assign('order',$order);
            $comment = $comment?$comment:['content'=>'','rate'=>0];
            $this->assign('comment',$comment);
            return $this->fetch();
        }
        if($comment){
            $this->error('订单已经评论过','/home/center/comment?id='.$orderid);
        }
        $content = $request->post('content')?trim($request->post('content')):'';
        $rate = $request->post('rate')?trim($request->post('rate')):0;
        $status = [];
        if(!$content){
            $status = ['code'=>0,'msg'=>'评论不能为空'];
        }else{
            $data = [
                'content'=>$content,
                'busid'=>$this->business['id'],
                'subid'=>$order['subid'],
                'rate'=>$rate,
                'orderid'=>$orderid
            ];
            $result = Comment::create($data);
            if($result){
                $status = ['code'=>1,'msg'=>'评论成功'];
            }else{
                $status = ['code'=>0,'msg'=>'评论失败'];
            }
        }
        return $status;
    }
    public function recharge(Request $request)
    {
        if($request->isGet())
        {
            $commissionModel = new Commission();
            $where = ['parentid'=>$this->business['id']];
            $withdrawed = $commissionModel->where($where)->where('status','1')->sum('amount');
            $notwithdraw = $commissionModel->where($where)->where('status','0')->sum('amount');
            $this->assign('withdrawed',$withdrawed);
            $this->assign('notwithdraw',$notwithdraw);
            return $this->fetch();
        }
    }
}